package com.cc.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.cc.blog.entity.SysUser;
import com.cc.blog.service.LoginService;
import com.cc.blog.service.SysUserService;
import com.cc.blog.utils.JWTUtils;
import com.cc.blog.vo.ErrorCode;
import com.cc.blog.vo.params.LoginParams;
import com.cc.blog.vo.Result;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SysUserService sysUserService;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    private static final String salt = "mszlu!@#";

    @Override
    public Result login(LoginParams loginParams) {
        /**
         * 1.检查用户名和密码是否合法
         * 2.根据用户名和密码去用户表中查询用户 是否存在
         * 3.如果不存在，登录失败
         * 4.如果存在，JWT生成token,返回给前端
         * 5.将token放入redis中
         * token:user信息 设置过期时间
         * 登录认证时，先判断token字符串是否合法，然后去redis认证是否存在
         */
        String account = loginParams.getAccount();
        String password = loginParams.getPassword();
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(),ErrorCode.PARAMS_ERROR.getMsg());
        }
        //密码加密
        password =  DigestUtils.md5Hex((password + salt));
        SysUser sysUser =  sysUserService.finduser(account,password);
        if (sysUser == null){
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(),ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
        String token = JWTUtils.createToken(sysUser.getId());
        redisTemplate.opsForValue().set("Token: " + token, JSON.toJSONString(sysUser),1, TimeUnit.DAYS);

        return Result.success(token);
    }

    @Override
    public SysUser checkToken(String token) {
        /**
         * 1 检查token是否合法
         * 2 检查token解析出来的对象是否存在
         * 3 redis 中是否存在token
         * 4 将redis中的token取出来并转化成对象
         */
        if (StringUtils.isBlank(token)){
            return null;
        }
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        if (stringObjectMap == null){
            return null;
        }
        String s = redisTemplate.opsForValue().get("Token: " + token);
        if (StringUtils.isBlank(s)){
            return null;
        }
        SysUser sysUser = JSON.parseObject(s, SysUser.class);
        return sysUser;
    }
}
